#include "database.h"

//Libraries
#include "logger.h"
#include "config.h"

Database::Database()
{
    //Mark db as loaded, if anything fails, unmark it
    this->loaded = true;

    //Choose SQLite
    db = QSqlDatabase::addDatabase("QSQLITE");

    //Get DB filename
    Config *config = Config::instance();
    QString dbFileName = config->getValue("db-file-name");

    //DB file exists?
    QFile file(dbFileName);
    bool initializeDb = !file.exists();

    //Set DB filename
    db.setDatabaseName(dbFileName);

    //Create logger
    Logger *logger = Logger::instance();

    if (!db.open()) {
        logger->log("Can't open database.",Logger::ERROR);
        this->loaded = false;
    }

    //Should we make needed tables in DB?
    if (initializeDb) {
        logger->log("Initializing DB...",Logger::NOTICE);

        QSqlQuery query;

        query.exec("create table users (name varchar(32), "
                                       "pass varchar(40), "
                                       "status int)");

        logger->log("DB Initialized.",Logger::NOTICE);
    }

    logger->log("DB loaded and ready.",Logger::NOTICE);
}
